<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="ReentrantReadWriteLock,StampedLock,">










<meta name="description" content="ReentrantReadWriteLock是一种基于lock的读写锁，在使用ReentrantLock时，它保证当前只有一个线程获取锁，但是有时候我们实际应用中会出现读多写少的场景，读于读之间都是读取同样的数据，如果使用ReentrantLock反而效率会低下，使用ReentrantReadWriteLock会很高效，它可以实现多个读锁同时进行，但是读与写和写于写互斥，只能有一个写锁线程在进行。">
<meta name="keywords" content="ReentrantReadWriteLock,StampedLock">
<meta property="og:type" content="article">
<meta property="og:title" content="Java并发编程七ReentrantReadWriteLock和StampedLock">
<meta property="og:url" content="https://zgsir.gitee.io/blog/2019/05/30/Java并发编程七ReentrantReadWriteLock和StampedLock/index.html">
<meta property="og:site_name" content="zhaoSir">
<meta property="og:description" content="ReentrantReadWriteLock是一种基于lock的读写锁，在使用ReentrantLock时，它保证当前只有一个线程获取锁，但是有时候我们实际应用中会出现读多写少的场景，读于读之间都是读取同样的数据，如果使用ReentrantLock反而效率会低下，使用ReentrantReadWriteLock会很高效，它可以实现多个读锁同时进行，但是读与写和写于写互斥，只能有一个写锁线程在进行。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-05-30T11:36:39.563Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Java并发编程七ReentrantReadWriteLock和StampedLock">
<meta name="twitter:description" content="ReentrantReadWriteLock是一种基于lock的读写锁，在使用ReentrantLock时，它保证当前只有一个线程获取锁，但是有时候我们实际应用中会出现读多写少的场景，读于读之间都是读取同样的数据，如果使用ReentrantLock反而效率会低下，使用ReentrantReadWriteLock会很高效，它可以实现多个读锁同时进行，但是读与写和写于写互斥，只能有一个写锁线程在进行。">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zgsir.gitee.io/blog/2019/05/30/Java并发编程七ReentrantReadWriteLock和StampedLock/">





  <title>Java并发编程七ReentrantReadWriteLock和StampedLock | zhaoSir</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">zhaoSir</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">一个不正经的后台开发攻城狮</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/blog/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zgsir.gitee.io/blog/blog/2019/05/30/Java并发编程七ReentrantReadWriteLock和StampedLock/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zhaoSir">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/blog/images/head.jpeg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zhaoSir">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Java并发编程七ReentrantReadWriteLock和StampedLock</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-05-30T19:35:16+08:00">
                2019-05-30
              </time>
            

            
              <span class="post-meta-divider">|</span>
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-check-o"></i>
              </span>
              
                <span class="post-meta-item-text">更新于&#58;</span>
              
              <time title="更新于" itemprop="dateModified" datetime="2019-05-30T19:36:39+08:00">
                2019-05-30
              </time>
            
          </span>
          
          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/Java并发/" itemprop="url" rel="index">
                    <span itemprop="name">Java并发</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-eye"></i> 阅读
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>次
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1.8k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  7分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="ReentrantReadWriteLock"><a href="#ReentrantReadWriteLock" class="headerlink" title="ReentrantReadWriteLock"></a>ReentrantReadWriteLock</h1><p>是一种基于lock的读写锁，在使用ReentrantLock时，它保证当前只有一个线程获取锁，但是有时候我们实际应用中会出现读多写少的场景，读于读之间都是读取同样的数据，如果使用ReentrantLock反而效率会低下，使用ReentrantReadWriteLock会很高效，它可以实现多个读锁同时进行，但是读与写和写于写互斥，只能有一个写锁线程在进行。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line">public class ReentrantReadWriteLockDemo &#123;</span><br><span class="line">  static class MyDemo&#123;</span><br><span class="line">        // 实例化读写锁 默认非公平</span><br><span class="line">        private ReentrantReadWriteLock lock=new ReentrantReadWriteLock();</span><br><span class="line">        // 模拟共享资源</span><br><span class="line">        private int number;</span><br><span class="line">        public void put(int number)  &#123;</span><br><span class="line">            // 写锁加锁</span><br><span class="line">            lock.writeLock().lock();</span><br><span class="line">            try &#123;</span><br><span class="line">                Thread.sleep(500);</span><br><span class="line">               this.number=number;</span><br><span class="line">                System.out.println(Thread.currentThread().getName()+&quot;:写入了&quot;+number);</span><br><span class="line">            &#125; catch (InterruptedException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125; finally &#123;</span><br><span class="line">                // 写锁释放锁</span><br><span class="line">                lock.writeLock().unlock();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        public int get()  &#123;</span><br><span class="line">            // 读写 加锁</span><br><span class="line">            lock.readLock().lock();</span><br><span class="line">            try &#123;</span><br><span class="line">                try &#123;</span><br><span class="line">                    Thread.sleep(1000);</span><br><span class="line">                &#125; catch (InterruptedException e) &#123;</span><br><span class="line">                    e.printStackTrace();</span><br><span class="line">                &#125;</span><br><span class="line">                System.out.println(Thread.currentThread().getName()+&quot;:读取了&quot;+number);</span><br><span class="line">                return number;</span><br><span class="line">            &#125;  finally &#123;</span><br><span class="line">                // 读锁解锁</span><br><span class="line">                lock.readLock().unlock();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    public static void main(String[] args) &#123;</span><br><span class="line">        MyDemo myDemo = new MyDemo();</span><br><span class="line">        // 三个写线程</span><br><span class="line">        for (int i = 0; i &lt; 3; i++) &#123;</span><br><span class="line">            new Thread(()-&gt; myDemo.put(new Random().nextInt(100)),&quot;写锁&quot;+i).start();</span><br><span class="line">        &#125;</span><br><span class="line">        // 十个读线程</span><br><span class="line">        for (int i = 0; i &lt; 10; i++) &#123;</span><br><span class="line">           new Thread(()-&gt; myDemo.get(),&quot;读锁&quot;+i).start();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>其中一次输出结果为：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">写锁2:写入了96</span><br><span class="line">读锁0:读取了96</span><br><span class="line">写锁1:写入了27</span><br><span class="line">读锁4:读取了27</span><br><span class="line">读锁6:读取了27</span><br><span class="line">读锁5:读取了27</span><br><span class="line">读锁3:读取了27</span><br><span class="line">读锁7:读取了27</span><br><span class="line">读锁1:读取了27</span><br><span class="line">读锁2:读取了27</span><br><span class="line">写锁0:写入了66</span><br><span class="line">读锁9:读取了66</span><br><span class="line">读锁8:读取了66</span><br></pre></td></tr></table></figure>
<h1 id="StampedLock"><a href="#StampedLock" class="headerlink" title="StampedLock"></a>StampedLock</h1><p>它是Jdk在1.8提供的一种读写锁，相比较ReentrantReadWriteLock性能更好，因为ReentrantReadWriteLock在读写之间是互斥的，使用的是一种悲观策略，在读线程特别多的情况下，会造成写线程处于饥饿状态，虽然可以在初始化的时候设置为true指定为公平，但是吞吐量又下去了，而StampedLock是提供了一种乐观策略，更好的实现读写分离，并且吞吐量不会下降。</p>
<h2 id="三种锁"><a href="#三种锁" class="headerlink" title="三种锁"></a>三种锁</h2><ul>
<li>写锁writeLock：<br><strong>是一个独占锁写锁，当一个线程获得该锁后，其他请求读锁或者写锁的线程阻塞， 获取成功后，会返回一个stamp（凭据）变量来表示该锁的版本，在释放锁时调用unlockWrite方法传递stamp参数。提供了非阻塞式获取锁tryWriteLock。</strong></li>
<li>悲观读锁readLock：<br><strong>是一个共享读锁，在没有线程获取写锁情况下，多个线程可以获取该锁。如果有写锁获取，那么其他线程请求读锁会被阻塞。悲观读锁会认为其他线程可能要对自己操作的数据进行修改，所以需要先对数据进行加锁，这是在读少写多的情况下考虑的。请求该锁成功后会返回一个stamp值，在释放锁时调用unlockRead方法传递stamp参数。提供了非阻塞式获取锁方法tryWriteLock。</strong></li>
<li>乐观读锁tryOptimisticRead：<br><strong>相对比悲观读锁，在操作数据前并没有通过CAS设置锁的状态，如果没有线程获取写锁，则返回一个非0的stamp变量，获取该stamp后在操作数据前还需要调用validate方法来判断期间是否有线程获取了写锁，如果是返回值为0则有线程获取写锁，如果不是0则可以使用stamp变量的锁来操作数据。由于tryOptimisticRead并没有修改锁状态，所以不需要释放锁。这是读多写少的情况下考虑的，不涉及CAS操作，所以效率较高，在保证数据一致性上需要复制一份要操作的变量到方法栈中，并且在操作数据时可能其他写线程已经修改了数据，而我们操作的是方法栈里面的数据，也就是一个快照，所以最多返回的不是最新的数据，但是一致性得到了保证。</strong></li>
</ul>
<hr>
<p>StampedLock支持三种锁在一定情况下进行相互转换。例如long tryConvertToWriteLock(long stamp)期望把stamp标示的锁升级为写锁，这个函数会在下面几种情况下返回一个有效的stamp（也就是晋升写锁成功）：　</p>
<ul>
<li><strong>如果当前锁已经是写锁，直接返回stamp。</strong></li>
<li><strong>如果当前是读锁，没有其他线程是读锁模式，返回一个写锁stamp。</strong></li>
<li><strong>如果当前是乐观读锁，并且没有线程获取写锁，返回一个stamp。</strong></li>
</ul>
<h2 id="注意点"><a href="#注意点" class="headerlink" title="注意点"></a>注意点</h2><p>由于StampedLock是读写锁都是不可冲入锁，所以在获取锁后释放锁前不再调用获取锁操作，避免造成线程的阻塞，当多个线程同时尝试获取写锁和读锁，是随机性的，没有一定的规则，并且该锁不是实现Lock或ReadWriteLock接口，而是在其内部自己维护了一个双向队列。</p>
<h2 id="案例说明"><a href="#案例说明" class="headerlink" title="案例说明"></a>案例说明</h2><p>下面一个例子是官方的提供的一个二维点的的例子：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br></pre></td><td class="code"><pre><span class="line"> package com.smart.home.ThreadTest;</span><br><span class="line"></span><br><span class="line">import java.util.concurrent.locks.StampedLock;</span><br><span class="line"></span><br><span class="line">class Point &#123;</span><br><span class="line">    // 内部定义表示坐标点</span><br><span class="line">    private double x, y;</span><br><span class="line">    //定义了StampedLock锁,</span><br><span class="line">    private final StampedLock s1 = new StampedLock();</span><br><span class="line"></span><br><span class="line">    // 写锁</span><br><span class="line">    public void move(double deltaX, double deltaY) &#123;</span><br><span class="line">        // 获得写锁 凭据</span><br><span class="line">        long stamp = s1.writeLock();</span><br><span class="line">        try &#123;</span><br><span class="line">            x += deltaX;</span><br><span class="line">            y += deltaY;</span><br><span class="line">        &#125; finally &#123;</span><br><span class="line">            // 释放写锁</span><br><span class="line">            s1.unlockWrite(stamp);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    // 乐观锁读</span><br><span class="line">    public double distanceFormOrigin() &#123;</span><br><span class="line">        //尝试乐观读 返回stamp凭证</span><br><span class="line">        long stamp = s1.tryOptimisticRead();</span><br><span class="line">        //读取x和y的值,这时候我们并不确定x和y是否是一致的 需要下一步再次判断</span><br><span class="line">        double currentX = x, currentY = y;</span><br><span class="line">        /**</span><br><span class="line">         * 判断stamp在读过程发生期间被修改过，如果没有被修改，则这次读取有效，直接return</span><br><span class="line">         * 如果stamp被修改过，则有可能其他线程改写了数据，会出现脏读，可以使用死循环使用乐观锁读，直到成功</span><br><span class="line">         * 也可以使用锁的级别，将乐观锁变为悲观锁</span><br><span class="line">         */</span><br><span class="line">        if (!s1.validate(stamp))</span><br><span class="line">            // 使用悲观锁读 如果有写线程那么该线程会挂起</span><br><span class="line">            stamp = s1.readLock();</span><br><span class="line">        try &#123;</span><br><span class="line">            currentX = x;</span><br><span class="line">            currentY = y;</span><br><span class="line">        &#125; finally &#123;</span><br><span class="line">            // 释放读锁</span><br><span class="line">            s1.unlockRead(stamp);</span><br><span class="line">        &#125;</span><br><span class="line">        return Math.sqrt(currentX * currentX + currentY * currentY);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    // 读锁转为写锁</span><br><span class="line">    public void moveIfAtOrigin(double newX, double newY) &#123;</span><br><span class="line">        // 读锁加锁 可以使用乐观读锁替代</span><br><span class="line">        long stamp = s1.readLock();</span><br><span class="line">        try &#123;</span><br><span class="line">            // 如果当前是原点 则修改</span><br><span class="line">            while (x == 0.0 &amp;&amp; y == 0.0) &#123;</span><br><span class="line">                // 尝试升级为写锁</span><br><span class="line">                long ws = s1.tryConvertToWriteLock(stamp);</span><br><span class="line">                // 升级成功 更新stamp凭据 设置坐标值 退出循环</span><br><span class="line">                if (ws != 0L) &#123;</span><br><span class="line">                    stamp = ws;</span><br><span class="line">                    x = newX;</span><br><span class="line">                    y = newY;</span><br><span class="line">                    break;</span><br><span class="line">                &#125; else &#123;</span><br><span class="line">                    // 升级失败 释放读锁，重新获取写锁，循环重试</span><br><span class="line">                    s1.unlockRead(stamp);</span><br><span class="line">                    stamp = s1.writeLock();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; finally &#123;</span><br><span class="line">            // 释放锁</span><br><span class="line">            s1.unlock(stamp);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>使用乐观锁读可以避免写锁处于饥饿状态，增加吞吐量，但是使用乐观锁读也是很容易犯错误的，在使用上必须保证以下顺序。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">//乐观读 返回stamp凭证</span><br><span class="line">  long stamp = lock.tryOptimisticRead();</span><br><span class="line">  // 复制变量到方法栈</span><br><span class="line">  CopyVariablesMethodStack();</span><br><span class="line">  // 校验stamp凭证</span><br><span class="line">  if (!lock.validate(stamp))&#123;</span><br><span class="line">      // 获取读锁</span><br><span class="line">      stamp = lock.readLock();</span><br><span class="line">      try &#123;</span><br><span class="line">      // 复制变量到方法栈</span><br><span class="line">          CopyVariablesMethodStack();</span><br><span class="line">      &#125; finally &#123;</span><br><span class="line">          // 释放读锁</span><br><span class="line">          lock.unlockRead(stamp);</span><br><span class="line">      &#125;</span><br><span class="line">  &#125;</span><br><span class="line">   // 操作操作复制到方法栈中的变量</span><br><span class="line">  ManipulateVariablesCopeMethodStack();</span><br></pre></td></tr></table></figure>

      
    </div>
    
    
    
	<div>
      
        
<div class="my_post_copyright">
  <script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>
  
  <!-- JS库 sweetalert 可修改路径 -->
  <script src="https://cdn.bootcss.com/jquery/2.0.0/jquery.min.js"></script>
  <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
  <p><span>本文标题:</span><a href="/blog/2019/05/30/Java并发编程七ReentrantReadWriteLock和StampedLock/">Java并发编程七ReentrantReadWriteLock和StampedLock</a></p>
  <p><span>文章作者:</span><a href="/" title="访问 zhaoSir 的个人博客">zhaoSir</a></p>
  <p><span>发布时间:</span>2019年05月30日 - 19:35</p>
  <p><span>最后更新:</span>2019年05月30日 - 19:36</p>
  <p><span>原始链接:</span><a href="/blog/2019/05/30/Java并发编程七ReentrantReadWriteLock和StampedLock/" title="Java并发编程七ReentrantReadWriteLock和StampedLock">https://zgsir.gitee.io/blog/2019/05/30/Java并发编程七ReentrantReadWriteLock和StampedLock/</a>
    <span class="copy-path" title="点击复制文章链接"><i class="fa fa-clipboard" data-clipboard-text="https://zgsir.gitee.io/blog/2019/05/30/Java并发编程七ReentrantReadWriteLock和StampedLock/" aria-label="复制成功！"></i></span>
  </p>
  <p><span>许可协议:</span><i class="fa fa-creative-commons"></i> <a rel="license" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">署名-非商业性使用-禁止演绎 4.0 国际</a> 转载请保留原文链接及作者。</p>  
</div>
<script> 
    var clipboard = new Clipboard('.fa-clipboard');
      $(".fa-clipboard").click(function(){
      clipboard.on('success', function(){
        swal({   
          title: "",   
          text: '复制成功',
          icon: "success", 
          showConfirmButton: true
          });
        });
    });  
</script>

      
</div>
   <div>
    
    <div>
    
        <div style="text-align:center;color: #111;font-size:16px;">-------------------------------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------------------------------</div>
    
</div>
    
    </div>
   

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/ReentrantReadWriteLock/" rel="tag"><i class="fa fa-tag"> </i> ReentrantReadWriteLock</a>
          
            <a href="/blog/tags/StampedLock/" rel="tag"><i class="fa fa-tag"> </i> StampedLock</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2019/05/28/Java并发编程六并发队列/" rel="next" title="Java并发编程六并发队列">
                <i class="fa fa-chevron-left"></i> Java并发编程六并发队列
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2019/06/03/Java并发编程八CountDownLatch、CyclicBarrier、Semaphore和Exchanger/" rel="prev" title="Java并发编程八CountDownLatch、CyclicBarrier、Semaphore和Exchanger">
                Java并发编程八CountDownLatch、CyclicBarrier、Semaphore和Exchanger <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC80NDMyMC8yMDg1Mw=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/blog/images/head.jpeg" alt="zhaoSir">
            
              <p class="site-author-name" itemprop="name">zhaoSir</p>
              <p class="site-description motion-element" itemprop="description">让人迷茫的原因的只有一个，那就是本该拼搏的年纪，想得太多，做得太少。</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">10</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">2</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">19</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#ReentrantReadWriteLock"><span class="nav-number">1.</span> <span class="nav-text">ReentrantReadWriteLock</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#StampedLock"><span class="nav-number">2.</span> <span class="nav-text">StampedLock</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#三种锁"><span class="nav-number">2.1.</span> <span class="nav-text">三种锁</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#注意点"><span class="nav-number">2.2.</span> <span class="nav-text">注意点</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#案例说明"><span class="nav-number">2.3.</span> <span class="nav-text">案例说明</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<script type="text/javascript" src="/blog/js/src/love.js"></script>
<div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">zhaoSir</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">博客字总数&#58;</span>
    
    <span title="博客字总数">20.8k</span>
  
  
</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  

  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

<script src="/blog/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","model":{"jsonPath":"/blog/live2dw/assets/koharu.model.json"},"display":{"position":"right","width":150,"height":320},"mobile":{"show":true},"log":false,"tagMode":false});</script></body>
</html>
